package cn.whit.blog.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.whit.blog.dao.VoteDao;
import cn.whit.blog.domain.User;
import cn.whit.blog.domain.Vote;
import cn.whit.blog.util.DynamicQuery;
import cn.whit.blog.util.JDBCUtils;
import cn.whit.blog.util.PageModel;
import cn.whit.blog.util.Parameter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class VoteDaoImpl implements VoteDao {

	@Override
	public Vote findById(String id) throws SQLException {
		String sql="select * from vote where id=?";
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		return qr.query(sql, new BeanHandler<Vote>(Vote.class),id);
	}

	@Override
	public List<Vote> findAll() throws SQLException {
		String sql="select * from vote";
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		return qr.query(sql, new BeanListHandler<Vote>(Vote.class));
	}


	@Override
	public List<Vote> findAllWithPageAndQuery(int startIndex, int pageSize, DynamicQuery query) throws Exception {
		String sql="select * from vote where 1=1 ";
		query.setBaseSql(sql);
		sql = query.generateSql();
		sql += " order by id desc limit  ? , ? ";
        //如果想排序，自行在sql后添加   
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		
		ArrayList<Parameter> parameters = query.getParameters();
		Object[] objs = new Object[parameters.size() + 2];
		int i = 0;
		for (Parameter p : parameters) {
			objs[i] = p.getValue();
			i++;
		}
		objs[i] = startIndex;
		objs[i+1] = pageSize;
		return qr.query(sql, new BeanListHandler<Vote>(Vote.class),objs);
	}

	@Override
	public int findTotalRecordsAndQuery(DynamicQuery query) throws Exception {
		String sql="select count(*) from vote where 1=1 ";
		query.setBaseSql(sql);
		sql = query.generateSql();
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		ArrayList<Parameter> parameters = query.getParameters();
		Object[] objs = new Object[parameters.size()];
		int i = 0;
		for (Parameter p : parameters) {
			objs[i] = p.getValue();
			i++;
		}
		Long num=(Long)qr.query(sql, new ScalarHandler(),objs);
		return num.intValue();
	}

	@Override
	public void save(Vote vote) throws SQLException {
		String sql="INSERT INTO vote(title,content,status,options,memo,startTime,endTime,createTime) "
				+ " VALUES(?,?,?,?,?,?,?,?)";
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		Object[] params={vote.getTitle(),vote.getContent(),vote.getStatus(),vote.getOptions(),
				vote.getMemo(),vote.getStartTime(),vote.getEndTime(),vote.getCreateTime()};
		qr.update(sql,params);
	}

	@Override
	public void update(Vote vote) throws SQLException {
		String sql="update vote set title= ? ,content=? ,status =? ,options =? ,memo =? , startTime =?  ,endTime =? ,createTime= ? WHERE id=?";
		Object[] params={vote.getTitle(),vote.getContent(),vote.getStatus(),vote.getOptions(),
				vote.getMemo(),vote.getStartTime(),vote.getEndTime(),vote.getCreateTime(),vote.getId()};
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		qr.update(sql,params);
	}

	@Override
	public void addOptionNum(String voteid, String optionid) {
		// 增加 指定投票中的指定投票选项的计数
		// [{"id":"4","name":"太失望了","num":0},{"id":"5","name":"还不如我自己烧","num":0}]
		// --->
		// [{"id":"4","name":"太失望了","num":1},{"id":"5","name":"还不如我自己烧","num":0}]
		
		try {
			
			Vote vote = findById(voteid);
			String options = vote.getOptions();
			//json 字符串 ---》  json对象
			JSONArray jsonArray = JSONArray.fromObject(options);
			System.out.println("旧的：");
			System.out.println(jsonArray);
			JSONObject fromObject = JSONObject.fromObject(jsonArray.get(Integer.parseInt(optionid)-1));
			int num =   Integer.parseInt(fromObject.get("num").toString());
			System.out.println(num);
			//投票选项对应的小计数据值+1
			fromObject.put("num", num + 1);
			//
			jsonArray.set(Integer.parseInt(optionid)-1, fromObject);
			System.out.println("新的：");
			System.out.println(jsonArray);
			vote.setOptions(jsonArray.toString());
			
			String sql="update vote set options =? WHERE id=?";
			Object[] params={vote.getOptions(),vote.getId()};
			QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
			qr.update(sql,params);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		VoteDaoImpl voteDaoImpl = new VoteDaoImpl();
		String optionid = "2";
		String voteid = "10";
		try {
			Vote vote = voteDaoImpl.findById(voteid);
			String options = vote.getOptions();
			//json 字符串 ---》  json对象
			JSONArray jsonArray = JSONArray.fromObject(options);
			System.out.println("旧的：");
			System.out.println(jsonArray);
			JSONObject fromObject = JSONObject.fromObject(jsonArray.get(Integer.parseInt(optionid)-1));
			int num =   Integer.parseInt(fromObject.get("num").toString());
			System.out.println(num);
			//投票选项对应的小计数据值+1
			fromObject.put("num", num + 1);
			//
			jsonArray.set(Integer.parseInt(optionid)-1, fromObject);
			System.out.println("新的：");
			System.out.println(jsonArray);
			 
//			System.out.println(Integer.parseInt(num));
//			HashMap<String, String> kv = (HashMap<String, String>) jsonObject.get(Integer.parseInt(optionid) - 1);
//			String value = kv.get("num");
//			System.out.println(Integer.parseInt(value));
			// json 对象 ---》json 字符串
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void deleteById(String s) throws SQLException {
		String sql=" delete from vote  WHERE id=? ";
		Object[] params={ s};
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		qr.update(sql,params);
	}


}
